package com.skillworld.webapp.web.pages.rest.tutorial;

import org.apache.tapestry5.annotations.ContentType;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.annotations.SessionState;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.services.Request;

import com.skillworld.webapp.model.tutorial.Tutorial.Status;
import com.skillworld.webapp.model.tutorialservice.AlreadyEvaluatedException;
import com.skillworld.webapp.model.tutorialservice.TutorialService;
import com.skillworld.webapp.model.util.InvalidArgumentException;
import com.skillworld.webapp.model.util.PermissionDeniedException;
import com.skillworld.webapp.web.util.ErrorMessages;
import com.skillworld.webapp.web.util.UserSession;

import es.udc.pojo.modelutil.exceptions.InstanceNotFoundException;

@ContentType("text/xml")
public class EvaluateTutorial
{   
    @SuppressWarnings("unused")
    @Property
    private String errorMessage = null;

    @Inject
    private TutorialService tutorialService;
   
    @SessionState(create=false)
    private UserSession userSession;
    
    private boolean userSessionExists;
    
    @Inject
    private Request request;
    

    void onPassivate()
    {
        return;
    }
    
    void onActivate()
    {
        if (!userSessionExists)
        {
            errorMessage = ErrorMessages.NOT_LOGGED_IN;
            return;
        }

        String tutParam = request.getParameter("tut");
        String decisionParam = request.getParameter("decision");
        String comment = request.getParameter("comment");
        
        if (tutParam == null || decisionParam == null || comment == null)
        {
            errorMessage = ErrorMessages.INVALID_ARGUMENTS;
            return;
        }
        
        try 
        {
            long tutorialId = Long.parseLong(tutParam);
            Status decision = Status.valueOf(decisionParam);
            tutorialService.evaluateTutorial(userSession.getUserId(),
                                                tutorialId, decision, comment);
        }
        catch (NumberFormatException e)
        { errorMessage = ErrorMessages.INVALID_ARGUMENTS; }
        catch (IllegalArgumentException e)
        { errorMessage = ErrorMessages.INVALID_ARGUMENTS; }
        catch (InstanceNotFoundException e)
        { errorMessage = ErrorMessages.TUTORIAL_NOT_FOUND; }
        catch (AlreadyEvaluatedException e)
        { errorMessage = ErrorMessages.ALREADY_EVALUATED; } 
        catch (PermissionDeniedException e) 
        { errorMessage = ErrorMessages.PERMISSION_DENIED; }
    }
}
